//
//  QKNetworkTool.swift
//  封装AFN请求
//
//  Created by iMac_Kurt on 16/8/15.
//  Copyright © 2016年 Kurt_Qi. All rights reserved.
//

import UIKit
import AFNetworking

enum QKRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class QKNetworkTool: AFHTTPSessionManager {
    /// 单例
    static let sharedTools: QKNetworkTool = {
        let url = NSURL(string: "http://httpbin.org/")
        
        let tool = QKNetworkTool(baseURL: url)
        
        tool.responseSerializer.acceptableContentTypes?.insert("text/html")
        
        return tool
    }()
}

// MARK: - 封装AFN网络请求
extension QKNetworkTool {
    // method是自定义的枚举类型
    func request(requestMethod method: QKRequestMethod, URLString urlStr: String, parameters: AnyObject?, finished:(result: AnyObject?, error: NSError?)->()) {
        // 将成功和失败的闭包抽出来
        let success = { (task: NSURLSessionDataTask, result: AnyObject?) -> () in
            finished(result: result, error: nil)
        }
        
        let faulure = { (task: NSURLSessionDataTask?, error: NSError) -> () in
            finished(result: nil, error: error)
            print("\(error)")
        }
        
        if method == QKRequestMethod.GET {
            GET(urlStr, parameters: parameters, progress: nil, success: success, failure: faulure)
        }else {
            POST(urlStr, parameters: parameters, progress: nil, success: success, failure: faulure)
        }
        
//        if method == "GET" {
//            GET(urlStr, parameters: parameters, progress: nil, success: { (task: NSURLSessionDataTask, result: AnyObject?) in
//                finished(result: result, error: nil)
//            }) { (task: NSURLSessionDataTask?, error: NSError) in
//                finished(result: nil, error: error)
//                print("\(error)")
//            }
//        }else {
//            POST(urlStr, parameters: parameters, progress: nil, success: { (task: NSURLSessionDataTask, result: AnyObject?) in
//                finished(result: result, error: nil)
//            }) { (task: NSURLSessionDataTask?, error: NSError) in
//                finished(result: nil, error: error)
//                print("\(error)")
//            }
//        }
        
//        GET(urlStr, parameters: parameters, success: { (task: NSURLSessionDataTask, result: AnyObject?) in
//            print("\(result)")
//        }) { (task: NSURLSessionDataTask?, error: NSError) in
//            print("\(error)")
//        }
    }
}
